<?php
require_once ('..' . DIRECTORY_SEPARATOR . 'initialize.php');
//GET Request
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
    include_once(Utils::getPath(array('shared', 'template.php')));
    include_once(Utils::getPath(array('repositories', 'challengeRepository.php')));
    $template = new Template('application');
    $template->initialize();

    $chaRep = new ChallengeRepository();
    $categories = $chaRep->getAllCategories();

    if (isset($_SESSION['oldform'])) {
        $oldform = $_SESSION['oldform'];
        unset($_SESSION['oldform']);
    }
    ?>
    <script type="text/javascript" src="<?php echo Utils::getUrl('scripts/challenge.js') ?>"></script>
    
    <h2>New challenge</h2>

    <form id="form-challenge" action="new.php" method="post" enctype="multipart/form-data" onsubmit="return validateChallengeNewForm(this);" >

        <div class="form-element">
            <label for="title">Title</label>
            <input type="text" id="title" name="title" value="<?php if (isset($oldform['title']))
        echo $oldform['title']; ?>" maxlength="128" onfocus="fieldHighlight(this, false)" />
        </div>
                
        <div class="form-element">
            <label for="category">Category</label>
            <select name="category" id="category" onfocus="fieldHighlight(this, false)" >
                <option value="0">Select one category</option>
                <?php
                $selectedCategory = isset($oldform['category']) ? $oldform['category'] : 0;
                foreach ($categories as $category) {
                    if ($selectedCategory != $category->getId()) {
                        ?>
                        <option value="<?php echo $category->getId(); ?>"><?php echo $category->getName(); ?></option>
                    <?php } else { ?>
                        <option value="<?php echo $category->getId(); ?>" selected="selected"><?php echo $category->getName(); ?></option>
                        <?php
                    }
                }
                ?>
            </select>
        </div>
        
        <div class="form-element">
            <label for="file">File (only <?php echo $strExtensions; ?> are accepted)</label>
            <input type="file"  id="file" name="file"/>
            <input type="hidden" name="extensions" value="<?php echo $strExtensions ?>"/>
        </div>

        <div class="form-element">
            <label for="description">Description</label>
            <textarea name="description" id="description" rows="8" cols="64" onkeypress="return imposeMaxLength(this, 512);" onfocus="fieldHighlight(this, false)" ><?php if (isset($oldform['description']))
                   echo $oldform['description']; ?></textarea>
        </div>

        <div class="form-element">
            <label for="solution">Solution</label>
            <textarea name="solution" id="solution" rows="8" cols="64" onkeypress="return imposeMaxLength(this, 512);" onfocus="fieldHighlight(this, false)" ><?php if (isset($oldform['solution']))echo $oldform['solution']; ?></textarea>
        </div>

        <div class="submit">
            <input type="submit" value="Submit"/>
        </div>

    </form>
    <?php
    $template->createPage('New challenge');
}
//POST Request
else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    include_once(Utils::getPath(array('repositories', 'challengeRepository.php')));

    foreach ($_POST as $key => $value) {
        $_SESSION['oldform'][$key] = $value;
    }

    $title = htmlspecialchars($_POST['title']);
    $description = htmlspecialchars($_POST['description']);
    $solution = $_POST['solution'];
    $category = $_POST['category'];

    $chaRep = new ChallengeRepository();

    $errorList = array();

    if (empty($title)) {
        $errorList[] = 'Empty title';
    } else if (strlen($title) > 128) {
        $errorList[] = 'The maximum size of the title is 128 characters';
    }
    if (empty($description)) {
        $errorList[] = 'Empty description';
    } else if (strlen($description) > 512) {
        $errorList[] = 'The maximum size of the description is 512 characters';
    }

    if (empty($solution)) {
        $errorList[] = 'Empty solution';
    } else if (strlen($solution) > 512) {
        $errorList[] = 'The maximum size of the solution is 512 characters';
    }

    if (isset($_FILES['file']) && $_FILES['file']['error'] == 0) {
        $name_file = $_FILES['file']['name'];
        $type_file = $_FILES['file']['type'];
        $size_file = $_FILES['file']['size']; //bytes
        $exte_file = end(explode(".", $name_file));
        $max_size = 5; //MB
        $accepted = in_array($exte_file, $extensions);
        if (!$accepted) {
            $errorList[] = "Only $strExtensions file extensions are accepted for upload";
        }
        if ($size_file > ($max_size * 1048576)) {//1048576 = 1024 * 1024
            $errorList[] = "File must be under $max_size MB in size";
        }
    }

    if ($category == 0) {
        $errorList[] = 'Select a category';
    }

    $exist = $chaRep->findByTitle($title, null, null, 0, 1);

    if (isset($exist)) {
        $errorList[] = 'A challenge with this title exists yet. Please change the title';
    }

    //Check for errors
    if ($errorList) {
        Utils::showErrorList($errorList);
        header("Location: new.php");
        exit();
    }

    //Everything is ok, so we can update database
    //Update database
    $newCha = new Challenge();

    $newCha->setIdAuthor($_SESSION['authenticatedId']);
    $newCha->setIdCategory($category);
    $newCha->setTitle($title);
    $newCha->setDescription($description);
    $newCha->setSolutionKey(md5($solution));

    $newCha = $chaRep->persist($newCha);


    if (isset($_FILES['file']) && !empty($_FILES['file']['name'])) {
        $cleanName = str_replace(chr(0), '', $_FILES['file']['name']); //Anti null-byte hack
        $src = '..'.DIRECTORY_SEPARATOR.'uploads'.DIRECTORY_SEPARATOR.'challenges'.DIRECTORY_SEPARATOR.$newCha->getId();
        mkdir($src, 0644,true);
        $srcdir = $src;
        $src .= DIRECTORY_SEPARATOR . $cleanName;
        $urlPath = '/uploads/challenges/'.$newCha->getId().'/'.$cleanName;
        if (!move_uploaded_file($_FILES['file']['tmp_name'], $src)) {
            $chaRep->remove($newCha);
            rmdir($srcdir);
            Utils::showError('An error occurred uploading your file, please try again in a moment.');
            header("Location: new.php");
            exit();
        }
        else{
            $newCha->setFilePath($urlPath);
            $newCha = $chaRep->persist($newCha);
        }
    }

    unset($_SESSION['oldform']);

    Utils::showInfo('Success!');
    header('Location: ' . Utils::getUrl('challenge/view.php?id=' . $newCha->getId()));
    exit();
}
?>